package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.OrdersPageQueryDTO;
import com.sky.dto.OrdersPaymentDTO;
import com.sky.dto.OrdersSubmitDTO;
import com.sky.entity.*;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.OrderBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.service.OrderService;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import com.sky.websocket.WebSocketServer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.*;

@Service
@Slf4j
public class OrderServiceImpl implements OrderService {
    @Autowired
    private AddressBookMapper addressBookMapper;
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private OrdersMapper ordersMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;

    private static final String AUTO_CANCEL = "订单已过期，自动取消订单";
    private static final String USER_CANCEL = "用户手动取消订单";

    @Autowired
    private WebSocketServer webSocketServer;
    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    public void paySuccess(String outTradeNo) {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();

        // 根据订单号查询当前用户的订单
        List<Orders> byNumberAndUserId = ordersMapper.getByNumberAndUserId(outTradeNo, userId,null);
        Orders ordersDB = byNumberAndUserId.get(0);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        ordersMapper.update(orders);
        //////////////////////////////////////////////
        Map map = new HashMap();
        map.put("type", 1);//消息类型，1表示来单提醒
        map.put("orderId", orders.getId());
        map.put("content", "订单号：" + outTradeNo);

        //通过WebSocket实现来单提醒，向客户端浏览器推送消息
        webSocketServer.sendToAllClient(JSON.toJSONString(map));
        ///////////////////////////////////////////////////
    }

    /**
     * 用户下单
     * @param ordersSubmitDTO
     * @return
     */
    @Override
    public OrderSubmitVO submitOrder(OrdersSubmitDTO ordersSubmitDTO) {
        //首先处理各种业务异常
        //地址为空时
        Long addressBookId = ordersSubmitDTO.getAddressBookId();
        AddressBook byId = addressBookMapper.getById(addressBookId);
        if (byId == null) {
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }

        //购物车为空时
        Long userId = BaseContext.getCurrentId();
        ShoppingCart shoppingCart = new ShoppingCart();
        shoppingCart.setUserId(userId);
        List<ShoppingCart> list = shoppingCartMapper.list(shoppingCart);
        if(list == null && list.size() == 0) {
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }

        //准备要插入的数据
        Orders orders = new Orders();
        orders.setStatus(Orders.PENDING_PAYMENT);
        orders.setUserId(BaseContext.getCurrentId());
        orders.setAddressBookId(addressBookId);
        orders.setOrderTime(LocalDateTime.now());
        orders.setPackAmount(ordersSubmitDTO.getPackAmount());
        orders.setPayMethod(ordersSubmitDTO.getPayMethod());
        orders.setPayStatus(Orders.UN_PAID);
        orders.setRemark(ordersSubmitDTO.getRemark());
        orders.setPhone(byId.getPhone());
        orders.setAddress(byId.getDetail());
        orders.setUserName(userMapper.getName(BaseContext.getCurrentId()));
        orders.setDeliveryStatus(ordersSubmitDTO.getDeliveryStatus());
        orders.setEstimatedDeliveryTime(ordersSubmitDTO.getEstimatedDeliveryTime());
        orders.setConsignee(byId.getConsignee());
        orders.setNumber(String.valueOf(System.currentTimeMillis()));
        orders.setAmount(ordersSubmitDTO.getAmount());
        orders.setPackAmount(ordersSubmitDTO.getPackAmount());
        if (ordersSubmitDTO.getTablewareStatus() == 0) {
            orders.setTablewareStatus(0);
            orders.setTablewareNumber(ordersSubmitDTO.getTablewareNumber());
        }
        orders.setTablewareStatus(ordersSubmitDTO.getTablewareStatus());

        //向订单表插入一条数据
        ordersMapper.insertNew(orders);

        //订单明细数据
        List<OrderDetail> orderDetailList = new ArrayList<>();
        for (ShoppingCart cart : list) {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(cart, orderDetail);
            orderDetail.setOrderId(orders.getId());
            orderDetailList.add(orderDetail);
        }

        //向明细表插入n条数据
        orderDetailMapper.insertBatch(orderDetailList);

        //清理购物车中的数据
        shoppingCartMapper.cleanAll(userId);

        //封装返回结果
        OrderSubmitVO orderSubmitVO = OrderSubmitVO.builder()
                .id(orders.getId())
                .orderNumber(orders.getNumber())
                .orderAmount(orders.getAmount())
                .orderTime(orders.getOrderTime())
                .build();

        return orderSubmitVO;
    }
    @Autowired
    private WeChatPayUtil weChatPayUtil;
    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.getById(userId);

        //调用微信支付接口，生成预支付交易单
        JSONObject jsonObject = weChatPayUtil.pay(
                ordersPaymentDTO.getOrderNumber(), //商户订单号
                new BigDecimal(0.01), //支付金额，单位 元
                "苍穹外卖订单", //商品描述
                user.getOpenid() //微信用户的openid
        );

        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
            throw new OrderBusinessException("该订单已支付");
        }

        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));

        return vo;
    }



    /**
     * 查看历史订单
     * @param page
     * @param pageSize
     * @param status
     * @return
     */
    @Override
    public PageResult checkOrders(Integer page, Integer pageSize, Integer status) {
        PageHelper.startPage(page,pageSize);
        Page<Orders> orders = (Page<Orders>) ordersMapper.getByNumberAndUserId(null, BaseContext.getCurrentId(), status);
        List<OrderVO> OrdersVOS = new ArrayList<>();
        for (Orders order : orders) {
            //如果订单超时，将其变成取消状态并给原因
            Date date = new Date(System.currentTimeMillis() - 900000);
            Instant checkTime = date.toInstant();
            Instant orderTime = order.getOrderTime().toInstant(ZoneOffset.of("+8"));
            if (orderTime.isBefore(checkTime) && order.getStatus() == 0) {
                if (order.getStatus() != Orders.CANCELLED){
                    ordersMapper.cancelOrder(order.getId(),AUTO_CANCEL,LocalDateTime.now());
                }
            }
            List<OrderDetail> orderDetail = orderDetailMapper.selectByOrderId(order.getId());
            OrderVO orderVO = new OrderVO();
            BeanUtils.copyProperties(order,orderVO);
            orderVO.setOrderDetailList(orderDetail);
            OrdersVOS.add(orderVO);
        }
        PageResult pageResult = new PageResult();
        pageResult.setTotal(orders.getTotal());
        pageResult.setRecords(OrdersVOS);
        log.info("输出{}",pageResult);
        return pageResult;
    }

    /**
     * 查看订单详情
     * @param id
     * @return
     */
    @Override
    public OrderVO checkOrder(Long id) {
        OrderVO orderVO = new OrderVO();
        Orders byNumberAndUserId = ordersMapper.selectById(id);
        List<OrderDetail> orderDetails = orderDetailMapper.selectByOrderId(id);
        BeanUtils.copyProperties(byNumberAndUserId,orderVO);
        orderVO.setOrderDetailList(orderDetails);
        return orderVO;
    }

    /**
     * 主动取消订单状态
     * @param id
     */
    @Override
    public void cancelOrder(Long id) {
        ordersMapper.cancelOrder(id,USER_CANCEL,LocalDateTime.now());
    }

    /**
     * 再来一单
     * @param id
     */
    @Override
    public void repetition(Long id) {
        List<OrderDetail> orderDetails = orderDetailMapper.selectByOrderId(id);
        for (OrderDetail orderDetail : orderDetails) {
            ShoppingCart shoppingCart = new ShoppingCart();
            BeanUtils.copyProperties(orderDetail,shoppingCart);
            shoppingCart.setId(null);
            shoppingCart.setCreateTime(LocalDateTime.now());
            shoppingCart.setUserId(BaseContext.getCurrentId());
            shoppingCartMapper.insert(shoppingCart);
        }
    }

    /**
     * 管理员查询用户订单
     * @param ordersPageQueryDTO
     * @return
     */
    @Override
    public PageResult conditionSearch(OrdersPageQueryDTO ordersPageQueryDTO) {
        PageHelper.startPage(ordersPageQueryDTO.getPage(),ordersPageQueryDTO.getPageSize());
        Page<OrderVO> orderVOS = ordersMapper.selectUserOrder(ordersPageQueryDTO);
        List<OrderVO> orderVOSPage = new ArrayList<>();
        for (OrderVO orderVO : orderVOS) {
            String orderMessage = new String();
            Long id = orderVO.getId();
            List<OrderDetail> orderDetails = orderDetailMapper.selectByOrderId(id);
            orderVO.setOrderDetailList(orderDetails);
            for (OrderDetail orderDetail : orderDetails) {
                String name = orderDetail.getName();
                Integer number = orderDetail.getNumber();
                orderMessage += ("[" + name + "x" + number +"]");
            }
            orderVO.setOrderDishes(orderMessage);
            orderVOSPage.add(orderVO);
        }
        PageResult pageResult = new PageResult();
        pageResult.setTotal(orderVOS.getTotal());
        pageResult.setRecords(orderVOSPage);
        log.info("返回{}",pageResult);
        return pageResult;
    }

    /**
     * 各个状态的订单统计
     * @return
     */
    @Override
    public OrderStatisticsVO statisticsResult() {
        Integer confirmed = ordersMapper.countConfirmed();
        Integer deliveryInProgress = ordersMapper.countdeliveryInProgress();
        Integer toBeConfirmed = ordersMapper.counttoBeConfirmed();
        OrderStatisticsVO orderStatisticsVO = new OrderStatisticsVO();
        orderStatisticsVO.setConfirmed(confirmed);
        orderStatisticsVO.setToBeConfirmed(toBeConfirmed);
        orderStatisticsVO.setDeliveryInProgress(deliveryInProgress);
        return orderStatisticsVO;
    }

    /**
     * 接单
     * @param order
     */
    @Override
    public void getOrder(Orders order) {
        order.setStatus(Orders.CONFIRMED);
        ordersMapper.update(order);
    }

    /**
     * 拒单
     * @param order
     */
    @Override
    public void rejectionOrder(Orders order) {
        order.setStatus(Orders.CANCELLED);
        order.setCancelTime(LocalDateTime.now());
        order.setCancelReason("商家拒单");
        ordersMapper.update(order);
    }

    /**
     * 商家取消订单
     * @param order
     */
    @Override
    public void adminCancelOrder(Orders order) {
        order.setStatus(Orders.CANCELLED);
        order.setCancelTime(LocalDateTime.now());
        ordersMapper.update(order);
    }

    /**
     * 派单
     * @param id
     */
    @Override
    public void sendOrder(Long id) {
        Orders order = new Orders();
        order.setId(id);
        order.setStatus(Orders.DELIVERY_IN_PROGRESS);
        ordersMapper.update(order);
    }

    /**
     * 完成订单
     * @param id
     */
    @Override
    public void completeOrder(Long id) {
        Orders order = new Orders();
        order.setId(id);
        order.setStatus(Orders.COMPLETED);
        ordersMapper.update(order);
    }

    /**
     * 催单
     * @param id
     */
    @Override
    public void reminder(Long id) {
        // 查询订单是否存在
        Orders orders = ordersMapper.getById(id);
        if (orders == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }

        //基于WebSocket实现催单
        Map map = new HashMap();
        map.put("type", 2);//2代表用户催单
        map.put("orderId", id);
        map.put("content", "订单号：" + orders.getNumber());
        webSocketServer.sendToAllClient(JSON.toJSONString(map));
    }
}
